﻿using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Devices;
using Microsoft.Maui.ApplicationModel;
using MauiApp1.Models;

namespace MauiApp1
{
    public partial class AdministratorPage : ContentPage, INotifyPropertyChanged
    {
        private ObservableCollection<LocationData> _locations;
        public ObservableCollection<LocationData> Locations
        {
            get => _locations;
            set
            {
                _locations = value;
                OnPropertyChanged();
            }
        }

        private bool _isLoading;
        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged();
            }
        }

        private const string AmapPickerUrl = "https://lbs.amap.com/console/show/picker";
        private readonly LocationClient _locationClient;

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public AdministratorPage()
        {
            InitializeComponent();
            _locations = new ObservableCollection<LocationData>();
            _locationClient = new LocationClient(Httpclass.ServerUrl);
            BindingContext = this;
            LoadLocationsFromServer();
        }

        private async Task LoadLocationsFromServer()
        {
            IsLoading = true;
            try
            {
                var (success, msg, locations) = await _locationClient.GetAllLocationsAsync(Httpclass.HttpLocationget);
                if (success)
                {
                    Locations.Clear();
                    foreach (var loc in locations)
                    {
                        Locations.Add(loc);
                    }
                }
                StatusLabel.Text = msg;
            }
            catch (Exception ex)
            {
                StatusLabel.Text = $"加载失败：{ex.Message}";
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async void OpenAmapPickerClicked(object sender, EventArgs e)
        {
            try
            {
                if (await Launcher.CanOpenAsync(AmapPickerUrl))
                {
                    await Launcher.OpenAsync(AmapPickerUrl);
                }
                else
                {
                    StatusLabel.Text = "无法打开高德地图，请检查网络";
                    StatusLabel.TextColor = Colors.Red;
                }
            }
            catch (Exception ex)
            {
                StatusLabel.Text = $"错误：{ex.Message}";
                StatusLabel.TextColor = Colors.Red;
            }
        }

        private async void DeleteClicked(object sender, EventArgs e)
        {
            if (sender is not Button deleteButton) return;
            var targetLocation = deleteButton.CommandParameter as LocationData;
            if (targetLocation == null) return;

            if (!await DisplayAlert("确认删除", $"确定要删除 {targetLocation.LocationName} 吗？", "是", "否"))
                return;

            IsLoading = true;
            try
            {
                var (isSuccess, message) = await _locationClient.DeleteLocationAsync(targetLocation.LocationId, Httpclass.HttpLocationDelete);
                StatusLabel.Text = isSuccess ? $"删除成功：{message}" : $"删除失败：{message}";
                StatusLabel.TextColor = isSuccess ? Colors.Green : Colors.Red;
                await LoadLocationsFromServer();
            }
            catch (Exception ex)
            {
                StatusLabel.Text = $"操作出错：{ex.Message}";
                StatusLabel.TextColor = Colors.Red;
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async void SaveLocationClicked(object sender, EventArgs e)
        {
            if (!ValidateInput()) return;

            IsLoading = true;
            try
            {
                var location = Resolver();
                if (location == null)
                {
                    StatusLabel.Text = "数据解析失败";
                    return;
                }

                var (isSuccess, message) = await _locationClient.UploadLocationDataAsync(location, Httpclass.HttpLocationset);
                StatusLabel.Text = isSuccess ? $"添加成功：{message}" : $"添加失败：{message}";
                StatusLabel.TextColor = isSuccess ? Colors.Green : Colors.Red;

                if (isSuccess)
                {
                    LocationTxt.Text = string.Empty;
                    RadiusEntry.Text = string.Empty;
                    LocationName.Text = string.Empty;
                }

                await LoadLocationsFromServer();
            }
            catch (Exception ex)
            {
                StatusLabel.Text = $"提交出错：{ex.Message}";
                StatusLabel.TextColor = Colors.Red;
            }
            finally
            {
                IsLoading = false;
            }
        }

        private bool ValidateInput()
        {
            if (string.IsNullOrWhiteSpace(LocationTxt.Text))
            {
                StatusLabel.Text = "经纬度不能为空";
                StatusLabel.TextColor = Colors.Red;
                return false;
            }

            var txt = LocationTxt.Text.Replace("，", ",").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (txt.Length < 2)
            {
                StatusLabel.Text = "经纬度格式错误（示例：116.404,39.915）";
                StatusLabel.TextColor = Colors.Red;
                return false;
            }

            if (!double.TryParse(txt[0].Trim(), out _) || !double.TryParse(txt[1].Trim(), out _))
            {
                StatusLabel.Text = "经纬度必须为数字";
                StatusLabel.TextColor = Colors.Red;
                return false;
            }

            if (!int.TryParse(RadiusEntry.Text, out int radius) || radius <= 0)
            {
                StatusLabel.Text = "半径必须为正整数";
                StatusLabel.TextColor = Colors.Red;
                return false;
            }

            if (string.IsNullOrWhiteSpace(LocationName.Text))
            {
                StatusLabel.Text = "位置名称不能为空";
                StatusLabel.TextColor = Colors.Red;
                return false;
            }

            return true;
        }

        private LocationData Resolver()
        {
            var txt = LocationTxt.Text.Replace("，", ",").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (!double.TryParse(txt[0].Trim(), out double lon) ||
                !double.TryParse(txt[1].Trim(), out double lat))
                return null;

            return new LocationData
            {
                Longitude = lon,
                Latitude = lat,
                LocationName = LocationName.Text,
                Radius = int.TryParse(RadiusEntry.Text, out int r) ? r : 0
            };
        }

        public class LocationClient
        {
            private readonly HttpClient _httpClient;
            private readonly string _serverUrl;
            private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            };

            public LocationClient(string serverUrl)
            {
                _serverUrl = serverUrl.TrimEnd('/');
                _httpClient = new HttpClient();
                _httpClient.Timeout = TimeSpan.FromMinutes(2);
            }

            private string GetFullUrl(string apiPath)
            {
                return $"{_serverUrl}{apiPath}";
            }

            public async Task<(bool success, string message)> UploadLocationDataAsync(LocationData location, string httpapi)
            {
                if (location == null)
                    return (false, "输入数据不能为空");

                try
                {
                    using (var content = new MultipartFormDataContent())
                    {
                        content.Add(new StringContent(location.LocationName), "LocationName");
                        content.Add(new StringContent(location.Latitude.ToString()), "Latitude");
                        content.Add(new StringContent(location.Longitude.ToString()), "Longitude");
                        content.Add(new StringContent(location.Radius.ToString()), "Radius");

                        var response = await _httpClient.PostAsync(GetFullUrl(httpapi), content);
                        var responseContent = await response.Content.ReadAsStringAsync();
                        var apiResponse = JsonSerializer.Deserialize<ApiResponse<object>>(responseContent, _jsonOptions);

                        if (response.IsSuccessStatusCode)
                        {
                            return (apiResponse?.Success ?? true, apiResponse?.Message ?? "上传成功");
                        }
                        else
                        {
                            return (false, apiResponse?.Message ?? $"服务器返回错误：{response.StatusCode}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    return (false, $"上传错误：{ex.Message}");
                }
            }

            public async Task<(bool Success, string Message, List<LocationData> Locations)> GetAllLocationsAsync(string httpapi)
            {
                try
                {
                    var response = await _httpClient.GetAsync(GetFullUrl(httpapi));
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonSerializer.Deserialize<ApiResponse<List<LocationData>>>(responseContent, _jsonOptions);

                    if (response.IsSuccessStatusCode)
                    {
                        return (
                            apiResponse?.Success ?? true,
                            apiResponse?.Message ?? "获取成功",
                            apiResponse?.Data ?? new List<LocationData>()
                        );
                    }
                    else
                    {
                        return (false, apiResponse?.Message ?? $"服务器返回错误：{response.StatusCode}", null);
                    }
                }
                catch (Exception ex)
                {
                    return (false, $"获取错误：{ex.Message}", null);
                }
            }

            public async Task<(bool success, string message)> DeleteLocationAsync(int locationId, string httpapi)
            {
                try
                {
                    string fullUrl = $"{GetFullUrl(httpapi)}{locationId}";
                    var response = await _httpClient.DeleteAsync(fullUrl);
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonSerializer.Deserialize<ApiResponse<object>>(responseContent, _jsonOptions);

                    if (response.IsSuccessStatusCode)
                    {
                        return (apiResponse?.Success ?? true, apiResponse?.Message ?? "删除成功");
                    }
                    else
                    {
                        return (false, apiResponse?.Message ?? $"服务器返回错误：{response.StatusCode}");
                    }
                }
                catch (Exception ex)
                {
                    return (false, $"删除错误：{ex.Message}");
                }
            }
        }
    }
}
